package com.sjz.han.industry.activites;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sjz.han.industry.MainActivity;
import com.sjz.han.industry.R;
import com.sjz.han.industry.base.AppConfig;
import com.sjz.han.industry.base.BaseActivity;
import com.sjz.han.industry.dialogs.PaytDialog;
import com.sjz.han.industry.entities.KeFuJsEntity;
import com.sjz.han.industry.entities.LoignEntity;
import com.sjz.han.industry.internetmanage.ReqestUrl;
import com.sjz.han.industry.utils.JsonUtils;
import com.sjz.han.industry.utils.SysUtils;
import com.sjz.han.industry.utils.ToastUtils;
import com.sjz.han.industry.utils.alipay.AuthResult;
import com.sjz.han.industry.utils.alipay.OrderInfoUtil2_0;
import com.sjz.han.industry.utils.alipay.PayResult;
import com.sjz.han.industry.wxapi.WeiXinPayMethod;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Map;

import okhttp3.Call;

//支付界面

//industry微信开放平台：
//        industryopenwx@163.com
//        app#123456
//支付宝开放平台
//industryopenwx@163.com
//        app#123456
public class PayActivity extends BaseActivity implements View.OnClickListener{
    private Button pay_btn;//支付
    private PaytDialog paytDialog;
    private TextView appjs_tv;
    public static PayActivity payActivity=null;

//    private WebView mWebView;
//    private ProgressBar progress_wheel;
    @Override
    protected int setLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initDatas() {
     appjs();
    }

    @Override
    protected void initViews() {
        payActivity=this;
        pay_btn=(Button)this.findViewById(R.id.pay_btn);
//        mWebView=(WebView)this.findViewById(R.id.appjs_contnet);
//        progress_wheel=(ProgressBar)this.findViewById(R.id.appjsprogress_wheel);
        appjs_tv=(TextView)this.findViewById(R.id.appjs_tv);
    }


    @Override
    protected void setLisener() {
        pay_btn.setOnClickListener(this);
    }

    @Override
    protected void onRetry() {

    }
//    private void setWebViewSetting(String content) {
//        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.getSettings().setAppCacheEnabled(true);
//        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
//        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        mWebView.setVerticalScrollBarEnabled(false);
//        mWebView.setVerticalScrollbarOverlay(false);
//        mWebView.setHorizontalScrollBarEnabled(false);
//        mWebView.setHorizontalScrollbarOverlay(false);
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//        mWebView.getSettings().setDomStorageEnabled(true);
////        mWebView.loadUrl("http://www.baidu.com");
//        mWebView.loadDataWithBaseURL(null, content,
//                "text/html", "utf-8", null);
//        mWebView.setWebViewClient(new WebViewClient() {
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//                progress_wheel.setVisibility(View.VISIBLE);
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
////                SysUtils.imgReset(mWebView);
//                progress_wheel.setVisibility(View.GONE);
//            }
//        });
//    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pay_btn://支付按钮
                paytDialog=new PaytDialog(this);
                paytDialog.setOnItemClickLicener(new PaytDialog.OnItemClickLicener() {
                    @Override
                    public void toWxPay() {
                        //微信支付
                       wxPay();
                    }

                    @Override
                    public void toZfbPay() {
                        //支付宝支付
                        zfbPay();
                    }
                });
                paytDialog.show();
                break;
        }
    }

    public void appjs(){
        OkHttpUtils
                .post()
                .url(ReqestUrl.APP_JS_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    KeFuJsEntity entity= JsonUtils.getObject(response,KeFuJsEntity.class);
                    if(entity!=null&&entity.code==0){
                        if(entity.data.customer.content!=null){
//                            setWebViewSetting(entity.data.customer.content);
                            appjs_tv.setText(Html.fromHtml(entity.data.customer.content));
                        }
                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }
    public void wxPay(){
        showLoadingDialog("正在支付...");
        OkHttpUtils
                .post()
                .url(ReqestUrl.WX_PAY_URL)
                .addParams("token",shareUtils.getToken())
                .addParams("money","0.01" )
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.popUpToast("服务器繁忙，请稍后重试!");
            }
            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    LoignEntity entity= JsonUtils.getObject(response,LoignEntity.class);
                    if(entity!=null&&entity.code==0){
                        WeiXinPayMethod.payReqByService(PayActivity.this,entity.data.appid,entity.data.partnerid,entity.data.prepayid,entity.data.noncestr,entity.data.timestamp,entity.data.sign);
                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }
    public void zfbPay(){
        showLoadingDialog("正在支付...");
        OkHttpUtils
                .post()
                .url(ReqestUrl.ZFB_PAY_URL)
                .addParams("token",shareUtils.getToken())
                .addParams("money","0.01" )
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.popUpToast("服务器繁忙，请稍后重试!");
            }
            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    LoignEntity entity= JsonUtils.getObject(response,LoignEntity.class);
                    if(entity!=null&&entity.code==0){
                        alpaypay(entity.msg);
//                        WeiXinPayMethod.payReqByService(PayActivity.this,entity.data.appid,entity.data.partnerid,entity.data.prepayid,entity.data.noncestr,entity.data.timestamp,entity.data.sign);
                    }else{
                        ToastUtils.popUpToast("服务器繁忙，请稍后重试!");
                    }
                }
            }
        });
    }
    /**
     * 支付宝支付
     * @param orderNo 商户网站唯一订单号
     * @param values  支付钱数
     * @param notifyUrl  支付宝服务器主动通知商户服务器里指定的页面http/https路径。
     */
    public void payV2(String orderNo, String values, String notifyUrl) {
        if (TextUtils.isEmpty(AppConfig.APPID) || (TextUtils.isEmpty(AppConfig.RSA2_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (AppConfig.RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(AppConfig.APPID, rsa2, orderNo, values, notifyUrl);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = AppConfig.RSA2_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    public void alpaypay(final String orderInfo) {
        if (TextUtils.isEmpty(AppConfig.APPID) || (TextUtils.isEmpty(AppConfig.RSA2_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
//        boolean rsa2 = (AppConfig.RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(AppConfig.APPID, rsa2, orderNo, values, notifyUrl);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        String privateKey = AppConfig.RSA2_PRIVATE;
//        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        final String orderInfo = orderInfo;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.popUpToast("支付成功");
                        shareUtils.setLevel("1");
                        startActivity(new Intent(PayActivity.this,MainActivity.class));
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.popUpToast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtils.popUpToast("授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtils.popUpToast("授权失败\n" + String.format("authCode:%s", authResult.getAuthCode()));

                    }
                }
                break;

            }
        }
    };
}
